import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Edit,
  Trash2,
  FileDown,
  Calendar,
  DollarSign,
  Clock,
  CheckCircle,
  AlertCircle,
  FileEdit,
  Loader2, // New import for loading spinner
} from "lucide-react";

import { format } from "date-fns";
import { createPageUrl } from "@/utils";
import { useNavigate } from "react-router-dom";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme"; // New import

import { useToast } from "@/components/ui/use-toast"; // New import

export default function SchemeCard({
  scheme,
  onEdit,
  onDelete,
  onDuplicate,
  onAnalyze,
}) {
  // Added onAnalyze prop
  const navigate = useNavigate();
  const { toast } = useToast(); // Initialize toast hook
  const [isGeneratingDoc, setIsGeneratingDoc] = useState(false); // State for document generation loading

  const getStatusConfig = (status) => {
    const statusConfigs = {
      notStarted: {
        label: "未开工",
        color: "bg-gray-100 text-gray-700",
        icon: <Clock className="w-3 h-3" />,
      },
      inProgress: {
        label: "已开工",
        color: "bg-blue-100 text-blue-700",
        icon: <AlertCircle className="w-3 h-3" />,
      },
      completed: {
        label: "已完工",
        color: "bg-green-100 text-green-700",
        icon: <CheckCircle className="w-3 h-3" />,
      },
    };
    return statusConfigs[status] || statusConfigs.notStarted;
  };

  const handleAnalyze = () => {
    console.log("🔍 SchemeCard handleAnalyze被调用");
    console.log("方案对象:", scheme);
    console.log("方案ID:", scheme?.id);

    if (!scheme?.id) {
      console.error("❌ 方案ID缺失，无法分析");
      toast({
        variant: "destructive",
        title: "分析失败",
        description: "方案信息不完整，无法进行分析。",
      });
      return;
    }

    const schemeId = scheme.id;
    console.log("📋 准备跳转分析，方案ID:", schemeId);

    // 直接调用父组件传下来的分析函数
    if (onAnalyze && typeof onAnalyze === "function") {
      console.log("✅ 调用父组件的onAnalyze函数");
      onAnalyze(schemeId);
    } else {
      console.log("⚠️ onAnalyze函数不存在，使用直接跳转");
      const analysisUrl = `${createPageUrl(
        "SchemeAnalysis"
      )}?id=${encodeURIComponent(schemeId)}`;
      console.log("直接跳转URL:", analysisUrl);

      navigate(analysisUrl, {
        state: {
          schemeId: schemeId,
          fromPage: "SchemeCard", // Added fromPage
          schemeName: scheme.name,
        },
      });
    }
  };

  const handleGenerateDocument = async () => {
    console.log(scheme, "schemescheme");

    if (!scheme || !scheme.id) {
      toast({
        variant: "destructive",
        title: "生成失败",
        description: "方案信息不完整，无法生成文档",
      });
      return;
    }
    if (!scheme.documentTemplateId) {
      toast({
        variant: "destructive",
        title: "未选择文档模板",
        description: "方案信息不完整，无法生成文档",
      });
      return;
    }

    setIsGeneratingDoc(true);
    try {
      const response = await ConstructionSchemeAPI.exportWord(scheme.id);
      if (!(response.data instanceof Blob)) {
        throw new Error("后端返回的不是二进制文件流，可能接口出错");
      }

      const rawFileName =
        response.headers["download-filename"] ||
        response.headers["Download-Filename"];
      let downloadFileName = rawFileName
        ? decodeURIComponent(rawFileName)
        : `施工方案_${scheme.name || scheme.id}.docx`;

      // 强制补充 .docx 后缀（避免后端返回的文件名没有后缀）
      if (!downloadFileName.endsWith(".docx")) {
        downloadFileName += ".docx";
      }

      // 3. 关键修复：创建Blob时指定正确的Word MIME类型
      const wordMimeType =
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const fileBlob = new Blob([response.data], { type: wordMimeType }); // 必须加 type！

      if (response.size) {
        toast({
          title: "未选择文档模板",
          description: "方案信息不完整，无法生成文档",
        });
      }
      if (rawFileName) {
        // 后端如果用了URLEncode，前端必须解码
        downloadFileName = decodeURIComponent(rawFileName);
      } else {
        // 兜底：如果头中没有，用默认名
        downloadFileName = `施工方案_${scheme.name}.docx`;
      }

      const url = window.URL.createObjectURL(fileBlob);
      const a = document.createElement("a");
      a.href = url;
      a.download = downloadFileName;
      document.body.appendChild(a);
      a.click();
      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error("生成Word文档失败:", error);
      toast({
        variant: "destructive",
        title: "生成失败",
        description: error.message || "生成Word文档时出错，请稍后重试",
      });
    } finally {
      setIsGeneratingDoc(false);
    }
  };

  const statusConfig = getStatusConfig(scheme.approvalStatus);

  return (
    <Card className="h-full flex flex-col hover:shadow-lg transition-shadow duration-200 border border-gray-200">
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <CardTitle className="text-lg leading-tight mb-2 line-clamp-2">
            {scheme.name}
          </CardTitle>
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          <Badge className={statusConfig.color}>
            {statusConfig.icon}
            <span className="ml-1">{statusConfig.label}</span>
          </Badge>
          {scheme.version && (
            <Badge variant="outline" className="text-xs">
              v{scheme.version}
            </Badge>
          )}
        </div>
      </CardHeader>

      <CardContent className="flex-1 flex flex-col justify-between">
        <div className="space-y-3">
          {/* 基本信息 */}
          <div className="grid grid-cols-3 gap-2 text-sm">
            {scheme.totalDuration && (
              <div className="flex items-center gap-1 text-gray-600">
                <Clock className="w-3 h-3" />
                <span>{scheme.totalDuration}天</span>
              </div>
            )}
            {/* {scheme.costEstimation && (
              <div className="flex items-center gap-1 text-green-600">
                <DollarSign className="w-3 h-3" />
                <span>{scheme.costEstimation}万</span>
              </div>
            )} */}
            {scheme.constructionStartDate && (
              <div className="flex items-center gap-1 text-gray-600">
                <Calendar className="w-3 h-3" />
                <span>
                  {format(new Date(scheme.constructionStartDate), "MM/dd")}
                </span>
              </div>
            )}
          </div>

          {/* 描述 */}
          {scheme.scopeOfWork && (
            <p className="text-sm text-gray-600 line-clamp-2">
              {scheme.scopeOfWork}
            </p>
          )}
        </div>

        {scheme.approver && (
          <div className="pt-3 border-t border-gray-100">
            <div className="flex items-center justify-between text-xs text-gray-500">
              <span>审批人: {scheme.approver}</span>
              {scheme.approvalDate && (
                <span>{format(new Date(scheme.approvalDate), "MM/dd")}</span>
              )}
            </div>
          </div>
        )}

        {/* Actions Button group below content */}
        {/* className="flex gap-2 pt-4" */}
        <div className="flex flex-col gap-2 pt-4">
          <Button
            onClick={() => handleAnalyze()}
            size="sm"
            className="bg-blue-600 hover:bg-blue-700 text-white w-full"
          >
            <Edit className="w-4 h-4 mr-2" />
            编辑
          </Button>
          {/* New Button for Word document generation */}

          <div className="flex gap-2">
            <Button
              onClick={handleGenerateDocument}
              disabled={isGeneratingDoc}
              size="sm"
              variant="outline"
              className="flex-1" // flex-1实现等分宽度
            >
              {isGeneratingDoc ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  生成中
                </>
              ) : (
                <>
                  <FileDown className="w-4 h-4 mr-2" />
                  导出Word
                </>
              )}
            </Button>

            <Button
              onClick={() => onDelete(scheme)}
              size="sm"
              variant="outline"
              className="flex-1"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              删除
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
